<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .flex {
      display: flex;
    }

    .symbol {
      display: inline-block;
      padding: 0 8px;
    }

    .tools {
      margin-left: 20px;
    }
  </style>
</head>

<body>
  <div class="flex">
    <input type="text" id="number1" class="entry"><span id="symbol_type" class="symbol"></span>
    <input type="text" id="number2" class="entry">

    <div class="tools">
      <button id="addition">+</button>
      <button id="subtraction">-</button>
      <button id="run">=</button>
    </div>
  </div>
  <h1 id="result"></h1>
  <script>
    var number1 = document.getElementById('number1')
    var number2 = document.getElementById('number2')
    var symbol_type = document.getElementById('symbol_type')

    var addition = document.getElementById('addition')
    var subtraction = document.getElementById('subtraction')
    var result = document.getElementById('result')
    var run = document.getElementById('run')

    // 判断是否为空
    function is_empty(value, errormsg) {
      if (!value) {
        alert(errormsg || '警告！您的值不许为空')
        return false
      }
      return true;
    }

    // 判断值是不是合法
    function is_number(value) {
      if (isNaN(value)) {
        alert('你的值不是一个数字')
        return false
      } else {
        return true
      }
    }

    // 运算符赋值
    addition.addEventListener('click', function () {
      symbol_type.innerText = addition.innerText
    })
    subtraction.addEventListener('click', function () {
      symbol_type.innerText = subtraction.innerText
    })

    // 得到计算结果
    run.addEventListener('click', function () {
      var n1 = number1.value;
      var n2 = number2.value;
      var symbol_name = symbol_type.innerText
      if (is_empty(n1) && is_empty(n2) && is_empty(symbol_name, '计算方式不许为空') && is_number(n1) && is_number(n2)) {
        debugger
        if (symbol_name === '+') {
          // 字符串加前需要转成数字
          result.innerText = Number(n1) + Number(n2)
          return
        } if (symbol_name === '-') {
          // 字符串相减会隐式转成数字，所以不用转类型
          result.innerText = n1 - n2
          return
        } else {
          alert('计算器异常，请选择正常的计算方式')
        }
      }
    })
  </script>
</body>

</html>